package com.linko.intelligent.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @program: craftsman-master
 * @description:
 * @author: 7
 * @create: 2020/6/817:06
 **/
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static final String DEV_ENV = "dev";
    private static final String TEST_ENV = "test";
    private static final String PROD_ENV = "prod";
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 实现ApplicationContextAware接口的回调方法，设置上下文环境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取对象
     *
     * @return Object 一个以所给名字注册的bean的实例 (service注解方式，自动生成以首字母小写的类名为bean name)
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * 判断当前环境是否是线上正式环境
     *
     * @param
     * @return boolean
     */
    public static boolean isProd() {
        return PROD_ENV.equals(getActiveProfile()) ? true : false;
    }

    /**
     * 获取当前环境变量
     *
     * @param
     * @return
     */
    public static String getActiveProfile() {
        return applicationContext.getEnvironment().getActiveProfiles()[0];
    }
}